home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip0493.zip / WB_FCOPY.C < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  77 lines

  1. /* 
  2. ** by: Walter Bright via Usenet C newsgroup
  3. **
  4. ** modified by: Bob Stout based on a recommendation by Ray Gardner
  5. **
  6. ** modified by: David Gersic to deal with binary files
  7. **
  8. ** There is no point in going to asm to get high speed file copies. Since it
  9. ** is inherently disk-bound, there is no sense (unless tiny code size is
  10. ** the goal). Here's a C version that you'll find is as fast as any asm code
  11. ** for files larger than a few bytes (the trick is to use large disk buffers):
  12. */
  13.  
  14. #include <stdlib.h>
  15. #include <io.h>
  16. #include <fcntl.h>
  17.  
  18. #if !defined(__ZTC__) && !defined(__TURBOC__)
  19.  #include <sys\types.h>
  20. #endif
  21.  
  22. #include <sys\stat.h>
  23.  
  24. #if Afilecopy
  25. int file_copy(from,to)
  26. #else
  27. int file_append(from,to)
  28. #endif
  29. char *from,*to;
  30. {       int fdfrom,fdto;
  31.         int bufsiz;
  32.  
  33.         fdfrom = open(from,O_RDONLY|O_BINARY,0);
  34.         if (fdfrom < 0)
  35.                 return 1;
  36. #if Afileappe
  37.         /* Open R/W by owner, R by everyone else        */
  38.         fdto=open(to,O_BINARY|O_CREAT|O_APPEND|O_RDWR,S_IREAD|S_IWRITE);
  39.         if (fdto < 0)
  40.             goto err;
  41. #else
  42.         fdto=open(to,O_BINARY|O_CREAT|O_TRUNC|O_RDWR,S_IREAD|S_IWRITE);
  43.         if (fdto < 0)
  44.             goto err;
  45. #endif
  46.  
  47.         /* Use the largest buffer we can get    */
  48.         for (bufsiz = 0x4000; bufsiz >= 128; bufsiz >>= 1)
  49.         {   register char *buffer;
  50.  
  51.             buffer = (char *) malloc(bufsiz);
  52.             if (buffer)
  53.             {   while (1)
  54.                 {   register int n;
  55.  
  56.                     n = read(fdfrom,buffer,bufsiz);
  57.                     if (n == -1)                /* if error             */
  58.                         break;
  59.                     if (n == 0)                 /* if end of file       */
  60.                     {   free(buffer);
  61.                         close(fdto);
  62.                         close(fdfrom);
  63.                         return 0;               /* success              */
  64.                     }
  65.                     if (n != write(fdto,buffer,(unsigned) n))
  66.                         break;
  67.                 }
  68.                 free(buffer);
  69.                 break;
  70.             }
  71.         }
  72. err2:   close(fdto);
  73.         remove(to);                             /* delete any partial file */
  74. err:    close(fdfrom);
  75.         return 1;
  76. }
  77.